/*
 * Tachometer.cpp
 *
 *  Created on: Jan 26, 2013
 *      Author: Drew Prevost
 */

#include "Tachometer.h"

Tachometer Tachometer::instance;

Tachometer& Tachometer::singleton()
{
  return instance;
}

Tachometer::Tachometer()
{
  nMillisLast = 0;
  nMillisCurrent = 0;
  nMillisDebounce = DFLT_TACH_DEBOUNCE;
  bInitialized = false;
}

Tachometer::~Tachometer()
{
}

void Tachometer::init(
                       int nIrqNum,
                       int nPin,
                       int nMode,
                       unsigned long nMillisDebounce /*= DFLT_TACH_DEBOUNCE*/)
{
  if ( !instance.bInitialized )
  {
    attachInterrupt( nIrqNum, tachISR, nMode );
    digitalWrite( nPin, ( nMode == FALLING ? HIGH : LOW ) );
    instance.nMillisDebounce = nMillisDebounce;
    instance.bInitialized = true;
  }
}

unsigned long Tachometer::getRpm()
{
  unsigned long nReturn = 0;

  unsigned long nDiff = ( nMillisCurrent - nMillisLast );
  nReturn = ( 60000 / nDiff );

  return nReturn;
}

void Tachometer::tachISR()
{
  if ( ( millis() - instance.nMillisCurrent ) >= instance.nMillisDebounce )
  {
    instance.nMillisLast = instance.nMillisCurrent;
    instance.nMillisCurrent = millis();
  }
}
